define([
    "dojo/_base/declare",
    "gistech/widgets/normalDialog/NormalDialog",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on",
    "dojo/_base/connect",
    "gistech/util/ajaxUtil",
    "dojo/dom-style","dojo/query","dojo/dom-class",
    "../OrganizationEditWidget/OrganizationEditWidget","dijit/Dialog","dojo/topic"],
    function(declare,NormalDialog,template,lang,style,domConstruct,on,eventconnect,ajaxUtil,domStyle,query,domClass,OrganizationEditWidget,Dialog,topic){
        return declare([NormalDialog],{
        	
            templateString:template,
            container:null,
            resetAttr:function(){
                this.inherited(arguments);
            },

            constructor:function (args) {
            	this.inherited(arguments);
            	this.container = args.container;
            	this.companyNode=null,
            	this.businessNode=null,
            	this.developmentNode=null,
            	
            	//
               	this.allVehicleData = new Object();
                this.map = args.map;
                this.container = args.container;
                this.currentPage=1;
                this.totalPage=1;
                this.currentSource=[];
            },
            
            postCreate:function(){
                this.inherited(arguments);
                //domConstruct.place(this.domNode, this.container);
                this.init();
                this.addEvents();

            },

            /**
             * 初始化
             */
            init:function () {
                this.companyNode=dojo.byId('company');
                this.businessNode=dojo.byId('business');
                this.developmentNode=dojo.byId('development');
            	this.loadData(true,true);
            	this.getOrganizationData(0,1);
            },
            
            
            addEvents:function(){
            	topic.subscribe("loadOrganizationData", lang.hitch(this, this.loadData));
            	on(dojo.byId('organizationName'),"keypress",dojo.hitch(this,this.nameKeyPress));
            	on(this.organizationBtnOk,"click",dojo.hitch(this,this.loadData));
            	on(this.organizationAddBtn,"click",dojo.hitch(this,this.organizationAdd));
            	
            },
            
            nameKeyPress:function(e){
            	if(e.keyCode==13){
            		this.loadData();
            	}
            	
            },
            
            /*
             * 加载数据
             */
            loadData:function(bCanClick,bShowLoading){
            	var organizationName= dojo.byId('organizationName').value;
                	ajaxUtil.request("../client/service/userOrganizationController/getOrganizationData","organizationName="+organizationName+"&rows=11&page=1",lang.hitch(this,function(result){
            		this.allVehicleData=lang.clone(result);
                	this.currentSource=this.allVehicleData.rows;
    	    		var len=this.allVehicleData.total;
    	    		var firstlen=len>10?10:len;
                	this._inittable(this.currentSource,0,firstlen);
                	this._initpager(len);
            	}),function(){
                    console.error("获取组织机构数据失败");
                });
                	
                	
                	
            },
            
            /*
             * 初始化表头
             */
            _inittableHeader:function(){
            	return '<tr><th style="width:38px">序号</th><th style="width:80px">组织机构名</th><th style="width:86px">机构类型</th><th style="width:85px">所属机构</th><th style="width:85px">负责人</th><th style="width:68px">操作</th> </tr>';
            },
            
            /*
             * 初始化表格
             */
            _inittable:function(source,firstnum,endnum){
            	
            	this.organizationGridtable.innerHTML="";
                var html="";
            	var headerHtml=this._inittableHeader();
            	html+=headerHtml;
            	var num = 0;
            	
            	for (var i=firstnum;i<endnum;i++){
        			var organization=source[i];
        			var typeName = organization.ORGANIZATION_TYPE;
        			if(typeName == "1"){
        				typeName ="集团";
        			}else if(typeName == "2"){
        				typeName ="事业部";
        			}else if(typeName == "3"){
        				typeName ="拓展组";
        			}
        			html+="<tr><td>"+(++num)+' </td><td>'+organization.ORGANIZATION_NAME+'</td><td>'+typeName+'</br><td>'+organization.PARENT_NAME+'</td><td>'+organization.MANAGER_USER_NAME+'</td><td><a class="updateOrganization">修改</a>&nbsp<a class="delOrganization">删除</a></td><td style="display:none">'+organization.ID+'</td><td style="display:none">'+organization.ORGANIZATION_MANAGER_ID+'</td><td style="display:none">'+organization.PARENT_ID+'</td>';
        			
        			html+="</tr>"; 
        		}
            	html=html.replace(/undefined/g,'');
            	this.organizationGridtable.innerHTML=html;
            	on(dojo.query('a.updateOrganization'),"click",dojo.hitch(this,this.updateOrganization));
            	on(dojo.query('a.delOrganization'),"click",dojo.hitch(this,this.delOrganization));
            },
            
            /*
             * 初始化分页
             */
            _initpager:function(len,startPage,endPager){
            	startPage=startPage||1;
            	endPager=endPager||15;
            	this.pager.innerHTML="";
            	domStyle.set(this.pager, "display", "block");
            	var html='<li><<</li><li><</li><li class="selectpager">'+startPage+'</li>';
            	
            	this.totalPage=parseInt((len-0.5)/10)+1;
            	if (this.totalPage<=15){
            		for (var i=2;i<=this.totalPage;i++){
                		html+='<li>'+i+'</li>';
                	}
            	}
            	else{
            		for (var i=startPage+1;i<=endPager;i++){
                		html+='<li>'+i+'</li>';
                	}
            	}
            	html+='<li>></li><li>>></li>';
            	this.pager.innerHTML=html;

            	query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(node,index){
            		on(node, 'click', lang.hitch(this,function (){
            			 switch (node.textContent)
            			 {
            			      case "<<":
            			    	  if (this.currentPage==1) return;
            			    	  this.currentPage=1;
            			    	  this._inittable(this.currentSource,0,10);
            			    	  
            			    	  if (this.currentPage>=startPage){
            			    		  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }else{
            			    		  this._initpager(len);
            			        	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }
            			    	  break;
            			      case "<":
            			    	  if (this.currentPage==1) return;
            			    	  this.currentPage--;
            			    	  var firstNum=(this.currentPage-1)*10;
            			    	  var lastNum=this.currentPage*10;
            			    	  this._inittable(this.currentSource,firstNum,lastNum);
            			    	  
            			    	  if (this.currentPage>=startPage){
            			    		  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(2+this.currentPage-startPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }else{
            			    		  this._initpager(len,startPage-1,endPager-1);
            			        	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }
            			    	  break;
            			      case ">":
            			    	  if (this.currentPage==this.totalPage) return;
            			    	  this.currentPage++;
            			    	  var firstNum=(this.currentPage-1)*10;
            			    	  var lastNum=this.currentPage*10;
            			          if (this.currentPage==this.totalPage)
            			        	  lastNum=this.currentSource.length;
            			          this._inittable(this.currentSource,firstNum,lastNum);
            			          if (this.currentPage<=endPager){
            			        	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(1+this.currentPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			          }else{
            			        	  this._initpager(len,startPage+1,endPager+1);
            			        	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==16) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			          }
            			    	  break;
            			      case ">>":
            			    	  if (this.currentPage==this.totalPage) return;
            			    	  this.currentPage=this.totalPage;
            			    	  
            			    	  var firstNum=(this.currentPage-1)*10;
            			          var lastNum=this.currentSource.length;
        			    	      this._inittable(this.currentSource,firstNum,lastNum);
        			    	      
        			    	      if (this.currentPage<=endPager){
        			    	    	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(1+this.totalPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
        			    	      }
        			    	      else{
        			    	    	  this._initpager(len,this.totalPage-14,this.totalPage);
        			    	    	  query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==16) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
        			    	      }
            			    	  break;
            			      default:
            			    	  this.currentPage=node.textContent;
            			          var firstNum=(this.currentPage-1)*10;
            			          var lastNum=this.currentPage*10;
            			          if (node.textContent==this.totalPage)
            			        	  lastNum=this.currentSource.length;
        			    	      this._inittable(this.currentSource,firstNum,lastNum);
        			    	      
        			    	      query(".organizationData-list ul.organizationPager li").forEach(lang.hitch(this,function(temnode,index){
        			    	    	  domClass.remove(temnode, "selectpager");
        			    	      }));
        			    	      domClass.add(node, "selectpager");
            			    	  break;
            			 }
            		}));
            	}));
            },
            
            organizationAdd:function(){
            	var organizationEditWidget = new OrganizationEditWidget(
            			{
            				pos:{l:Math.ceil(document.body.clientWidth)/2-419,t:110} 
            			},
            			dojo.byId("organizationEditDialog"));
            		organizationEditWidget.setTitle("组织机构新增");
            		organizationEditWidget.startup();
            },
            
            updateOrganization:function(e){
            	var flag = e.target.innerText;
        		var parent = e.target.parentNode.parentNode;//tr
        		var organizationName = e.target.parentNode.parentNode.children[1].innerText;//名称
        		var typeName = e.target.parentNode.parentNode.children[2].innerText.trim();//机构类型
        		var parentName = e.target.parentNode.parentNode.children[3].innerText;//所属机构名称
        		var menagerName = e.target.parentNode.parentNode.children[4].innerText;//负责人名称
        		var organizationId = e.target.parentNode.parentNode.children[6].innerText;//ID
        		var menagerId = e.target.parentNode.parentNode.children[7].innerText;//负责人ID
        		var parentId = e.target.parentNode.parentNode.children[8].innerText;//上级机构ID
        		
    			if(typeName == "集团"){
    				typeName ="1";
    			}else if(typeName == "事业部"){
    				typeName ="2";
    			}else if(typeName == "拓展组"){
    				typeName ="3";
    			}
        		
            	if(flag=='修改'){
                    	var organizationEditWidget = new OrganizationEditWidget(
                    			{
                    				pos:{l:Math.ceil(document.body.clientWidth)/2-419,t:110},
                    			    organizationName:organizationName,
                    			    typeName:typeName,
                    			    parentName:parentName,
                    			    menagerName:menagerName,
                    			    organizationId:organizationId,
                    			    menagerId:menagerId,
                    			    parentId:parentId
                    			
                    			},
                    			dojo.byId("organizationEditDialog"));
                    	organizationEditWidget.setTitle("组织机构修改");
                    	organizationEditWidget.startup();
 
            	}else{
            		
            		var cValue = company.childNodes[0].value;
            		var bValue = business.childNodes[0].value;
            		var dValue = develop.childNodes[0].value;
            		var existFlag =e.target.parentNode.parentNode.children[10].innerText;
            		
            		var param = "id="+userId+"&companyId="+cValue+"&businessId="+bValue+"&developId="+dValue+"&existFlag="+existFlag;
            		this.updateOrganizationOrganization(param);
            		
            	}
            	 
            },
            
            loadSelect:function(e){
            	var value = e.target.value;
                ajaxUtil.request("../client/service/userOrganizationController/getOrganization","parentId="+value,lang.hitch(this,function(result){
                    var Store = eval(result.result);
                     var StoreHTML = "<option selected=\"selected\" value=\"\">请选择</option>";
                     for(var i=0; i<Store.length;i++){
                         StoreHTML += "<option value='"+Store[i].id+"'>"+Store[i].organizationName+"</option>";
                     }
                     if(e.target.attributes[3].value==1){
                    	 dojo.byId('2'+e.target.id.substr(1)).innerHTML = StoreHTML;
                     }else if(e.target.attributes[2].value==2){
                    	 dojo.byId('3'+e.target.id.substr(1)).innerHTML = StoreHTML;
                     }
                 }),function(){
                    console.error("获取下拉列表失败");
                 });
            	
            },
            
 
            
            getOrganizationData:function(parentId,type){
            	
                ajaxUtil.request("../client/service/userOrganizationController/getOrganization","parentId="+parentId,lang.hitch(this,function(result){
                    var Store = eval(result.result);
                     var StoreHTML = "<option selected=\"selected\" value=\"\">请选择</option>";
                     for(var i=0; i<Store.length;i++){
                         StoreHTML += "<option value='"+Store[i].id+"'>"+Store[i].organizationName+"</option>";
                     }
                     if(type==1){
                    	 this.company.innerHTML = StoreHTML;
                     }
                    
                 }),function(){
                    console.error("获取下拉列表失败");
                 });
 
            },
            
            delOrganization : function(e){
 
            	var mes = confirm("确认删除该数据？")
            	if(mes){
            		var param  = "organizationId="+e.target.parentNode.parentNode.children[6].innerText;
                	ajaxUtil.request("../client/service/userOrganizationController/deleteOrganization",param,lang.hitch(this,function(result){
                		if(result.success){
                			this.loadData();
                			alert('操作成功');
                		}else{
                			alert('操作失败');
                		}
                	}),function(){
                		alert('操作失败');
                        console.error("操作数据失败");
                    });
            	}else{
            		
            	}
            	
            	   
            },
            

            
            startup:function(){
                this.inherited(arguments);
            },
            closeDialog:function(){
    			this.inherited("closeDialog",arguments);
    			this.destroy();
    		}

    });
});

